package com.red.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.red.context.BaseContext;
import com.red.dto.HomePageQueryDTO;
import com.red.entity.Orders;
import com.red.entity.Products;
import com.red.mapper.OrderMapper;
import com.red.mapper.ProductsMapper;
import com.red.result.PageResult;
import com.red.service.OrderService;
import com.red.vo.OrderVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ProductsMapper productsMapper;


    /**
     * 查询所有订单
     * @return
     */
    public List<OrderVO> selectAll() {
        Long user_id = BaseContext.getCurrentId();
        QueryWrapper<Orders> qw = new QueryWrapper<>();
        qw.eq("user_id",user_id);
        qw.orderByDesc("created_at");
        List<Orders> ordersList = orderMapper.selectList(qw);

        if (ordersList == null && ordersList.size()==0){
            return null;
        }
        List<OrderVO> arrayList = new ArrayList<>();
        for (Orders orders : ordersList) {
            OrderVO orderVO = new OrderVO();
            Products products = productsMapper.selectById(orders.getProductId());
            BeanUtils.copyProperties(orders,orderVO);
            orderVO.setProductsName(products.getName());
            orderVO.setDescription(products.getDescription());
            orderVO.setImageUrl(products.getImageUrl());
            orderVO.setCategoryId(products.getCategoryId());
            orderVO.setAPrice(BigDecimal.valueOf(products.getPrice()));
            arrayList.add(orderVO);
        }

        return arrayList;
    }

    /**
     * 分页查询
     * @param dto
     * @return
     */
    public PageResult pageQuery(HomePageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(),dto.getPageSize());

        Page<OrderVO> page = orderMapper.pageQuery(dto);

        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 修改状态
     * @param orders
     */
    public void updateStatus(Orders orders) {
        orderMapper.updateById(orders);
    }
}
